package com.netty.rpc.runner;

import com.netty.rpc.encode.Decode;
import com.netty.rpc.encode.Encode;
import com.netty.rpc.handler.NettyServerHandler;
import com.netty.rpc.req.CalcRequest;
import com.netty.rpc.resp.CalcResponse;
import com.netty.rpc.resp.Response;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.Signal;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.netty.rpc.annotation.RpcService;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class NettyServer implements CommandLineRunner, ApplicationContextAware {

    private Map<String, Object> servicesMap = new ConcurrentHashMap<>();

    @Override
    public void run(String... args) throws Exception {

        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new Decode(CalcRequest.class));
                            ch.pipeline().addLast(new NettyServerHandler(servicesMap));
                            ch.pipeline().addLast(new Encode());

                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(8081).sync().addListener(future -> {
                System.out.println("netty server started success ...");
            });
            channelFuture.channel().closeFuture().sync();
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        servicesMap =  applicationContext.getBeansWithAnnotation(RpcService.class);
    }
}
